package com.steven.sync.mianshi;


import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 固定同步容器，put get ，getcount方法，支持2个生产者，10个消费者调用 阻塞调用
 * Condition :有多个等待队列
 */
public class Test2_p_c_condition {

    static LinkedList list = new LinkedList<>();

    static final private Integer MAX =10;





    public void  put (Object o){
        list.add(o);
        System.out.println(Thread.currentThread().getName()+"生产");
    }
    public void  get (Object o){
        list.removeFirst();
        System.out.println(Thread.currentThread().getName()+"消费");
    }
    public Integer  getCount(){
       return list.size();
    }

    public static void main(String[] args) {

        Lock lock =new ReentrantLock();
        Condition pr = lock.newCondition();
        Condition cu = lock.newCondition();

        Test2_p_c_condition test2Pcnotify = new Test2_p_c_condition();

        //生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    try {
                        lock.lock();
                        while (test2Pcnotify.getCount() == MAX) {
                           pr.await();
                        }
                        test2Pcnotify.put(new Object());
                        System.out.println(Thread.currentThread().getName() + "-生产者生产，数量为:" + test2Pcnotify.getCount());
                        cu.signalAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }

            }, "P" + i).start();
        }


        //消费者
        for (int i = 0; i < 9; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    try {
                        lock.lock();
                        while (test2Pcnotify.getCount() == 0) {
                            cu.await();
                        }
                        test2Pcnotify.get(new Object());
                        System.out.println(Thread.currentThread().getName() + "-消费者消费，数量为：" + test2Pcnotify.getCount());
                        pr.signalAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                       lock.unlock();
                    }

                }
            }, "C" + i).start();
        }




    }




}
